package com.cd2cd.code_template.util;

import com.alibaba.fastjson.JSONObject;
import com.cd2cd.code_template.configuration.constants.ServiceCode;
import com.cd2cd.code_template.configuration.security.TokenUser;
import com.cd2cd.code_template.vo.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;

@Slf4j
public class CommUtils {

	public static String randomUUID() {
		return UUID.randomUUID().toString().replace("-", "").toLowerCase();
	}

	public static String serialId(String prefix) {
		// 32位
		String dStr = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 17
		String uuid = prefix + randomUUID(); // 18
		return uuid.substring(0, 15) + dStr;
	}

	public static String getClientIp() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String md5Encode(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	public static HttpServletResponse getResponse() {
        HttpServletResponse response=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
	}

	/**
	 * 4~6位随机码
	 * @param num
	 * @return
	 */
	public static String randomCode(Integer num) {
		int nn = Optional.ofNullable(num).orElse(6);
		Random rand = new Random();
		StringBuilder s = new StringBuilder(nn);
		for (int i = 0; i < nn; i++) {
			s.append((int) (rand.nextInt(9)));
		}
		return s.toString();
	}

	public static void main(String[] args) {
		System.out.println(md5Encode("admin111111"));
	}

	public static TokenUser getLoginUserInfo() {
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Authentication authentication = securityContext.getAuthentication();
		if (authentication == null) {
			return null;
		}
		Object principal = authentication.getPrincipal();
		if (principal != null && principal instanceof TokenUser) {
			return (TokenUser) principal;
		}
		return null;
	}

    public static void returnCode(HttpServletResponse response, ServiceCode serviceCode) {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("code", serviceCode.code);
		jsonObj.put("msg", serviceCode.msg);
		response.setContentType("application/json;charset=UTF-8");
		try {
			response.getWriter().println(jsonObj.toString());
		}catch (IOException ee) {
			ee.printStackTrace();
		}
    }

    public static void printObjJson(HttpServletResponse response, BaseRes res) {
		response.setContentType("application/json;charset=UTF-8");
		if (res.getCode() == ServiceCode.TOKEN_INVALID.code) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
		}
		try {
			response.getWriter().println(JSONObject.toJSONString(res));
		}catch (IOException ee) {
			ee.printStackTrace();
		}
	}
}
